package com.paas.form.core.model;

import com.paas.common.util.StringUtil;
import com.paas.form.core.element.field.FormDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@EqualsAndHashCode(callSuper = true)
@Data
public class ElForm extends ElementUI {

    private String _model;

    private String _ref;

    private String _rules;

    private Integer _labelWidth;

    public ElForm(FormDataModel formDataModel, int indentNum) {
        this._model = formDataModel.getFormModel();
        this._ref = formDataModel.getFormRef();
        this._rules = formDataModel.getFormRules();
        this._labelWidth = formDataModel.getLabelWidth();
        this.indentNum = indentNum;
    }

    @Override
    public void getElHtml(StringBuilder str) {

    }

    @Override
    public void getStartTagElHtml(StringBuilder str) {
        String codeTemplate = String.join("", Collections.nCopies(indentNum, "\t")) + "<el-form${[model]}${[rules]}${[ref]}${[label_width]}>";
        //
        Map<String, Object> params = new HashMap<>();
        params.put("model", StringUtil.isNotEmpty(this._model) ? " :model=\"" + this._model + "\"" : null);
        params.put("rules", StringUtil.isNotEmpty(this._ref) ? " :rules=\"" + this._rules + "\"" : null);
        params.put("ref", StringUtil.isNotEmpty(this._rules) ? " ref=\"" + this._ref + "\"" : null);
        params.put("label_width", " label-width=\"" + this._labelWidth + "px"+"\" ");

        //
        ExpressionParser parser = new SpelExpressionParser();
        TemplateParserContext parserContext = new TemplateParserContext("${", "}");
        str.append(parser.parseExpression(codeTemplate, parserContext).getValue(params, String.class));
        str.append("\n");
    }

    @Override
    public void getEndTagElHtml(StringBuilder str) {
        String codeTemplate = String.join("", Collections.nCopies(indentNum, "\t")) + "</el-form>";
        str.append(codeTemplate);
        str.append("\n");
    }
}